import { Directive, AfterViewInit, ElementRef, OnInit } from '@angular/core';

@Directive({
    // tslint:disable-next-line:directive-selector
    selector: '[focusinput]'
})
// tslint:disable-next-line:directive-class-suffix
export class FocusInput implements AfterViewInit {
    /**
     * 当input创建时选中
     * @param elem
     */
    constructor(
        private elem: ElementRef
    ) { }

    ngAfterViewInit() {
        const elem = this.elem.nativeElement;
        if (!elem || !elem.tagName) return;
        // 当前为input,直接focus
        if (('' + elem.tagName).toLowerCase() === 'input') {
            this.focus(elem);
            return;
        }
        // 当前非input 查找下面的元素看是否有input
        const inputElem = elem.querySelector('input');
        if (inputElem) {
            this.focus(inputElem);
        }
    }
    focus(elem) {
        // console.log(elem);
        elem.focus();
        setTimeout(x => {
            elem.select();
        });
    }
}
